<template>
  <div class="course-manage-container">
    <el-card shadow="never" class="header-card">
      <div class="page-header">
        <div class="header-content">
          <el-icon class="header-icon" :size="28"><Setting /></el-icon>
          <div class="header-text">
            <h2>课程管理</h2>
            <p>创建和管理课程内容</p>
          </div>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="showDialog = true">
            <el-icon><Plus /></el-icon>
            创建课程
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 筛选区域 -->
    <el-card shadow="never" class="filter-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="课程名称">
          <el-input v-model="searchForm.title" placeholder="请输入课程名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="课程分类">
          <el-select v-model="searchForm.category" placeholder="请选择" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="技术开发" value="tech" />
            <el-option label="产品运营" value="product" />
            <el-option label="市场营销" value="marketing" />
            <el-option label="财务管理" value="finance" />
          </el-select>
        </el-form-item>
        <el-form-item label="课程状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="已发布" value="published" />
            <el-option label="草稿" value="draft" />
            <el-option label="已下架" value="offline" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 课程列表 -->
    <el-card shadow="never">
      <el-table :data="tableData" stripe>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="课程封面" width="120">
          <template #default="{ row }">
            <el-image
              :src="row.cover || '/default-course.jpg'"
              fit="cover"
              style="width: 80px; height: 60px; border-radius: 4px;"
              :preview-src-list="[row.cover]"
            />
          </template>
        </el-table-column>
        <el-table-column prop="title" label="课程名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="categoryName" label="分类" width="120" />
        <el-table-column prop="teacher" label="讲师" width="100" />
        <el-table-column prop="lessonsCount" label="课时数" width="100" />
        <el-table-column prop="studentCount" label="学员数" width="100" />
        <el-table-column prop="rating" label="评分" width="120">
          <template #default="{ row }">
            <el-rate v-model="row.rating" disabled show-score :max="5" text-color="#ff9900" />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button link type="success" @click="handleManageChapters(row)">
              <el-icon><Document /></el-icon>
              章节
            </el-button>
            <el-button link type="warning" @click="handlePublish(row)" v-if="row.status === 'draft'">
              <el-icon><Upload /></el-icon>
              发布
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 20px; justify-content: flex-end;"
      />
    </el-card>

    <!-- 新建/编辑课程对话框 -->
    <el-dialog
      v-model="showDialog"
      :title="dialogTitle"
      width="900px"
      destroy-on-close
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="课程名称" prop="title">
              <el-input v-model="form.title" placeholder="请输入课程名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程分类" prop="category">
              <el-select v-model="form.category" placeholder="请选择分类" style="width: 100%">
                <el-option label="技术开发" value="tech" />
                <el-option label="产品运营" value="product" />
                <el-option label="市场营销" value="marketing" />
                <el-option label="财务管理" value="finance" />
                <el-option label="人力资源" value="hr" />
                <el-option label="通用技能" value="general" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="课程描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入课程简介" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="授课讲师" prop="teacher">
              <el-select v-model="form.teacher" placeholder="请选择讲师" style="width: 100%">
                <el-option label="张三" value="张三" />
                <el-option label="李四" value="李四" />
                <el-option label="王五" value="王五" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程难度" prop="difficulty">
              <el-select v-model="form.difficulty" placeholder="请选择难度" style="width: 100%">
                <el-option label="初级" value="初级" />
                <el-option label="中级" value="中级" />
                <el-option label="高级" value="高级" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="课程时长" prop="duration">
              <el-input v-model="form.duration" placeholder="如：30小时">
                <template #append>小时</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课时数量" prop="lessonsCount">
              <el-input-number v-model="form.lessonsCount" :min="1" :max="999" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="课程封面">
          <el-upload
            class="cover-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
            accept="image/*"
          >
            <img v-if="form.cover" :src="form.cover" class="cover-image" />
            <div v-else class="cover-placeholder">
              <el-icon><Plus /></el-icon>
              <span>上传封面</span>
            </div>
          </el-upload>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否推荐">
              <el-switch v-model="form.isHot" active-text="是" inactive-text="否" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否新课">
              <el-switch v-model="form.isNew" active-text="是" inactive-text="否" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="课程详情" prop="detailDescription">
          <el-input v-model="form.detailDescription" type="textarea" :rows="6" placeholder="请输入课程详细介绍" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button @click="handleSaveDraft">保存草稿</el-button>
        <el-button type="primary" @click="handleSave">保存并发布</el-button>
      </template>
    </el-dialog>

    <!-- 章节管理对话框 -->
    <el-dialog
      v-model="showChapterDialog"
      title="章节管理"
      width="800px"
      destroy-on-close
    >
      <div class="chapter-manage">
        <el-button type="primary" @click="showAddChapterDialog = true" style="margin-bottom: 16px;">
          <el-icon><Plus /></el-icon>
          添加章节
        </el-button>

        <el-collapse v-model="activeChapters" accordion>
          <el-collapse-item
            v-for="(chapter, index) in currentCourseChapters"
            :key="index"
            :name="index"
          >
            <template #title>
              <div class="chapter-header">
                <span>第{{ index + 1 }}章：{{ chapter.title }}</span>
                <div class="chapter-actions" @click.stop>
                  <el-button link type="primary" @click="handleEditChapter(chapter, index)">编辑</el-button>
                  <el-button link type="danger" @click="handleDeleteChapter(index)">删除</el-button>
                </div>
              </div>
            </template>
            <div class="lessons-manage">
              <el-button size="small" @click="showAddLessonDialog = true; currentChapterIndex = index">
                <el-icon><Plus /></el-icon>
                添加课时
              </el-button>
              <el-table :data="chapter.lessons" style="margin-top: 12px;">
                <el-table-column prop="title" label="课时名称" />
                <el-table-column prop="duration" label="时长" width="100" />
                <el-table-column prop="type" label="类型" width="100">
                  <template #default="{ row }">
                    <el-tag size="small">{{ row.type || '视频' }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="150">
                  <template #default="{ row, $index }">
                    <el-button link type="danger" size="small" @click="handleDeleteLesson(index, $index)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-collapse-item>
        </el-collapse>

        <el-empty v-if="currentCourseChapters.length === 0" description="还没有章节，添加一个吧" />
      </div>
    </el-dialog>

    <!-- 添加章节对话框 -->
    <el-dialog v-model="showAddChapterDialog" title="添加章节" width="500px">
      <el-form :model="chapterForm" label-width="100px">
        <el-form-item label="章节名称">
          <el-input v-model="chapterForm.title" placeholder="请输入章节名称" />
        </el-form-item>
        <el-form-item label="章节描述">
          <el-input v-model="chapterForm.description" type="textarea" :rows="3" placeholder="请输入章节描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddChapterDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSaveChapter">确定</el-button>
      </template>
    </el-dialog>

    <!-- 添加课时对话框 -->
    <el-dialog v-model="showAddLessonDialog" title="添加课时" width="500px">
      <el-form :model="lessonForm" label-width="100px">
        <el-form-item label="课时名称">
          <el-input v-model="lessonForm.title" placeholder="请输入课时名称" />
        </el-form-item>
        <el-form-item label="课时类型">
          <el-select v-model="lessonForm.type" placeholder="请选择类型" style="width: 100%">
            <el-option label="视频" value="video" />
            <el-option label="文档" value="document" />
            <el-option label="音频" value="audio" />
            <el-option label="直播" value="live" />
          </el-select>
        </el-form-item>
        <el-form-item label="课时时长">
          <el-input v-model="lessonForm.duration" placeholder="如：30分钟" />
        </el-form-item>
        <el-form-item label="课时内容">
          <el-input v-model="lessonForm.content" type="textarea" :rows="4" placeholder="请输入课时内容或视频链接" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddLessonDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSaveLesson">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Setting, Plus, Search, Refresh, Edit, Document, Upload, Delete
} from '@element-plus/icons-vue'

// 搜索表单
const searchForm = reactive({
  title: '',
  category: '',
  status: ''
})

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 50
})

// 表格数据
const tableData = ref([
  {
    id: 1,
    title: 'Vue 3 从入门到精通',
    categoryName: '技术开发',
    category: 'tech',
    teacher: '张三',
    duration: '30小时',
    lessonsCount: 45,
    studentCount: 1256,
    rating: 4.8,
    difficulty: '中级',
    cover: '',
    status: 'published',
    isNew: true,
    isHot: true
  },
  {
    id: 2,
    title: '产品思维与方法论',
    categoryName: '产品运营',
    category: 'product',
    teacher: '李四',
    duration: '20小时',
    lessonsCount: 30,
    studentCount: 856,
    rating: 4.6,
    difficulty: '初级',
    cover: '',
    status: 'published',
    isNew: false,
    isHot: true
  },
  {
    id: 3,
    title: 'React开发实战',
    categoryName: '技术开发',
    category: 'tech',
    teacher: '王五',
    duration: '28小时',
    lessonsCount: 38,
    studentCount: 523,
    rating: 4.7,
    difficulty: '中级',
    cover: '',
    status: 'draft',
    isNew: true,
    isHot: false
  }
])

// 对话框
const showDialog = ref(false)
const showChapterDialog = ref(false)
const showAddChapterDialog = ref(false)
const showAddLessonDialog = ref(false)
const formRef = ref(null)
const currentRow = ref(null)
const currentCourseChapters = ref([])
const activeChapters = ref([0])
const currentChapterIndex = ref(0)

const dialogTitle = computed(() => currentRow.value ? '编辑课程' : '创建课程')

// 表单
const form = reactive({
  title: '',
  category: '',
  description: '',
  teacher: '',
  difficulty: '',
  duration: '',
  lessonsCount: 1,
  cover: '',
  isHot: false,
  isNew: false,
  detailDescription: ''
})

const chapterForm = reactive({
  title: '',
  description: ''
})

const lessonForm = reactive({
  title: '',
  type: 'video',
  duration: '',
  content: ''
})

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择课程分类', trigger: 'change' }],
  teacher: [{ required: true, message: '请选择授课讲师', trigger: 'change' }]
}

const uploadUrl = '/api/upload'

// 方法
const handleSearch = () => {
  console.log('搜索', searchForm)
  ElMessage.success('查询成功')
}

const handleReset = () => {
  Object.assign(searchForm, {
    title: '',
    category: '',
    status: ''
  })
  handleSearch()
}

const handleEdit = (row) => {
  currentRow.value = row
  Object.assign(form, {
    title: row.title,
    category: row.category,
    description: row.description || '课程描述...',
    teacher: row.teacher,
    difficulty: row.difficulty,
    duration: row.duration.replace('小时', ''),
    lessonsCount: row.lessonsCount,
    cover: row.cover,
    isHot: row.isHot,
    isNew: row.isNew,
    detailDescription: '课程详细介绍...'
  })
  showDialog.value = true
}

const handleManageChapters = (row) => {
  currentRow.value = row
  // 模拟加载章节数据
  currentCourseChapters.value = [
    {
      title: '基础入门',
      description: '学习基础知识',
      lessons: [
        { id: 1, title: '课程简介', duration: '15分钟', type: 'video' },
        { id: 2, title: '环境搭建', duration: '20分钟', type: 'video' }
      ]
    }
  ]
  showChapterDialog.value = true
}

const handlePublish = (row) => {
  ElMessageBox.confirm('确定要发布该课程吗？', '提示', {
    type: 'success'
  }).then(() => {
    row.status = 'published'
    ElMessage.success('发布成功')
  }).catch(() => {})
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该课程吗？', '提示', {
    type: 'warning'
  }).then(() => {
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
    }
    ElMessage.success('删除成功')
  }).catch(() => {})
}

const handleSave = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success('保存并发布成功')
      showDialog.value = false
    }
  })
}

const handleSaveDraft = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success('保存草稿成功')
      showDialog.value = false
    }
  })
}

const handleCoverSuccess = (response) => {
  form.cover = response.url
  ElMessage.success('封面上传成功')
}

const handleSaveChapter = () => {
  if (!chapterForm.title) {
    ElMessage.warning('请输入章节名称')
    return
  }
  currentCourseChapters.value.push({
    title: chapterForm.title,
    description: chapterForm.description,
    lessons: []
  })
  chapterForm.title = ''
  chapterForm.description = ''
  showAddChapterDialog.value = false
  ElMessage.success('章节添加成功')
}

const handleEditChapter = (chapter, index) => {
  chapterForm.title = chapter.title
  chapterForm.description = chapter.description
  showAddChapterDialog.value = true
}

const handleDeleteChapter = (index) => {
  ElMessageBox.confirm('确定要删除该章节吗？', '提示', {
    type: 'warning'
  }).then(() => {
    currentCourseChapters.value.splice(index, 1)
    ElMessage.success('删除成功')
  }).catch(() => {})
}

const handleSaveLesson = () => {
  if (!lessonForm.title) {
    ElMessage.warning('请输入课时名称')
    return
  }
  const chapter = currentCourseChapters.value[currentChapterIndex.value]
  if (chapter) {
    chapter.lessons.push({
      id: Date.now(),
      title: lessonForm.title,
      type: lessonForm.type,
      duration: lessonForm.duration,
      content: lessonForm.content
    })
    Object.assign(lessonForm, {
      title: '',
      type: 'video',
      duration: '',
      content: ''
    })
    showAddLessonDialog.value = false
    ElMessage.success('课时添加成功')
  }
}

const handleDeleteLesson = (chapterIndex, lessonIndex) => {
  ElMessageBox.confirm('确定要删除该课时吗？', '提示', {
    type: 'warning'
  }).then(() => {
    currentCourseChapters.value[chapterIndex].lessons.splice(lessonIndex, 1)
    ElMessage.success('删除成功')
  }).catch(() => {})
}

const getStatusName = (status) => {
  const map = {
    published: '已发布',
    draft: '草稿',
    offline: '已下架'
  }
  return map[status] || status
}

const getStatusType = (status) => {
  const map = {
    published: 'success',
    draft: 'info',
    offline: 'danger'
  }
  return map[status] || ''
}
</script>

<style scoped>
.course-manage-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  color: #409EFF;
}

.header-text h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.header-text p {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #909399;
}

.filter-card {
  margin-bottom: 20px;
}

.cover-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  overflow: hidden;
  transition: border-color 0.3s;
}

.cover-uploader:hover {
  border-color: #409EFF;
}

.cover-image {
  width: 300px;
  height: 180px;
  display: block;
  object-fit: cover;
}

.cover-placeholder {
  width: 300px;
  height: 180px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
  color: #8c939d;
}

.chapter-manage {
  max-height: 500px;
  overflow-y: auto;
}

.chapter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  font-weight: 500;
}

.chapter-actions {
  display: flex;
  gap: 8px;
}

.lessons-manage {
  padding: 12px;
  background-color: #f5f7fa;
}
</style>

